import json
import time

import requests
from redis import Redis
from wechatpy import WeChatOAuth, WeChatClient
from wechatpy.session.redisstorage import RedisStorage
from config.config import redisIp, redisPort, WX


class RedisService:
    def __init__(self):
        self.redis = Redis(redisIp, redisPort)
        self.session = RedisStorage(redis=self.redis)
        self.oauth = WeChatOAuth(
            app_id=WX.get('appid'),
            secret=WX.get('appsecret'),
            redirect_uri=WX.get('base_url') + WX.get('redirect_url')
        )
        self.client = WeChatClient(WX.get("appid"), WX.get("appsecret"), session=self.session)

    def get_access_token(self):
        access_token = self.session.get('access_token', '')
        if not access_token:
            access_token = self.client.fetch_access_token()['access_token']
            self.session.set('access_token', access_token, 7000)

        return access_token

    def post_template_of_unread_message(self, openid, device_id, name, timestamp, message_type):
        date_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp + 8*3600))

        if message_type == 1:
            message_str = ''
        elif message_type == 2:
            message_str = '监听'
        elif message_type == 3:
            message_str = '图片'
        else:
            message_str = ''

        data = {
            "touser": openid,
            "template_id": "tp80iNSBFsTPObqK1NJ2zN3CxcTSMUZLnmLjSXt4rhY",  # 模板ID
            "url": "http://weixin.pbani.com/wx/index?action=record&device_id=" + device_id,
            # "miniprogram":{
            #   "appid":"wx67afc56d7f6cfac0",  #待使用上线小程序appid
            #   "path":"pages/reserve/mgr/mgr"
            # },
            "data": {
                "first": {
                    "value": "您好，您关注的设备",
                    "color": "#173177"
                },
                "keyword1": {
                    "value": name,
                    "color": "#173177"
                },
                "keyword2": {
                    "value": date_time,
                    "color": "#173177"
                },
                "keyword3": {
                    "value": "未读%s消息提醒" % (message_str, ),
                    # "value": "未读消息提醒",
                    "color": "#173177"
                },
                "remark": {
                    "value": "已向您发送消息，请注意查看",
                    "color": "#173177"
                }
            }
        }
        json_template = json.dumps(data)
        print(json_template)
        access_token = self.get_access_token()
        url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token
        try:
            response = requests.post(url, data=json_template, timeout=5)
            # 拿到返回值
            print(response)
            err_code = response.json().get("errcode")
            print("test--", response.json())
            if err_code == 0:
                return True
            else:
                return False
        except:
            return False
